package bootload

import (
	"bytes"
	"cabinet/pkg/global"
	"cabinet/pkg/log"
	"fmt"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"strings"
)

const (
	configType            = "yml"
	configDir             = "config"
	developmentConfig     = "config.dev.yml"
	stagingConfig         = "config.stage.yml"
	productionConfig      = "config.prod.yml"
	defaultConnectTimeout = 5
)

func InitConfig() {
	v := viper.New()
	// read development config as default config
	v.SetConfigType(configType)
	// read from system
	bs := readConfig(configDir, developmentConfig)
	if err := v.ReadConfig(bytes.NewReader(bs)); err != nil {
		panic(errors.Wrapf(err, "initialize config failed, config dir: %s", configDir))
	}
	settings := v.AllSettings()
	for index, setting := range settings {
		v.SetDefault(index, setting)
	}

	// unmarshal to global.Conf
	if err := v.Unmarshal(&global.Conf); err != nil {
		panic(errors.Wrapf(err, "initialize config failed, config dir: %s", configDir))
	}

	if strings.TrimSpace(global.Conf.System.UrlPrefix) == "" {
		global.Conf.System.UrlPrefix = "api"
	}

	if strings.TrimSpace(global.Conf.System.ApiVersion) == "" {
		global.Conf.System.ApiVersion = "v1"
	}

	global.Conf.System.Base = fmt.Sprintf("/%s/%s", global.Conf.System.UrlPrefix, global.Conf.System.ApiVersion)

	if strings.TrimSpace(global.Conf.Mysql.TablePrefix) != "" && strings.HasSuffix(global.Conf.Mysql.TablePrefix, "_") {
		global.Conf.Mysql.TablePrefix = strings.TrimSuffix(global.Conf.Mysql.TablePrefix, "_")
	}

	log.Log().Info("initialize config success, config dir: %s", configDir)
}

func readConfig(dir, filename string) (bs []byte) {
	if filename == "" {
		return
	}
	f := filepath.Join(dir, filename)
	// read from system
	bs, err := os.ReadFile(f)
	if err != nil {
		log.Log().Error("read file %s from system failed", f)
		panic(errors.Wrapf(err, "read file %s from system failed", f))
	}
	return
}
